package com.salmon.study.iot;


import akka.actor.AbstractActor;
import akka.actor.Props;
import com.salmon.study.iot.group.message.DeviceRegistered;
import com.salmon.study.iot.group.message.RequestTrackDevice;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

@Slf4j
public class Device extends AbstractActor {


    private final String groupId;

    private final String deviceId;

    public Device(String groupId, String deviceId) {
        this.groupId = groupId;
        this.deviceId = deviceId;
    }

    public static Props props(String groupId, String deviceId) {
        // props 调用create 方法， 第二个参数是构造方法中的参数列表
        return Props.create(Device.class, groupId, deviceId);
    }

    Optional<Double> lastTemperatureReading = Optional.empty();

    @Override
    public void preStart() {
        log.info("Device actor {}-{} started", groupId, deviceId);
    }

    @Override
    public void postStop() {
        log.info("Device actor {}-{} stopped", groupId, deviceId);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(RecordTemperature.class, this::recordTemperature)
                .match(ReadTemperature.class, this::readTemperature)
                .match(RequestTrackDevice.class, this::requestTrackDevice).build();
    }


    private void readTemperature(ReadTemperature r) {
        sender().tell(new RespondTemperature(r.getRequestId(), lastTemperatureReading), self());
    }

    private void recordTemperature(RecordTemperature r) {
        log.info("recorded temperature reading {} with {}", r.getValue(), r.getRequestId());
        lastTemperatureReading = Optional.of(r.getValue());
        sender().tell(new TemperatureRecorded(r.getRequestId()), self());
    }

    private void requestTrackDevice(RequestTrackDevice r) {
        if(this.groupId.equals(r.getGroupId()) && this.deviceId.equals(r.getDeviceId())) {
            sender().tell(new DeviceRegistered(), self()); // 发送注册成功消息
        } else {
            log.warn("Ignore TraceDevice request for {}-{}. this actor is responsible for {}-{}.",
                    r.getGroupId(), r.getDeviceId(), this.groupId, this.deviceId);
        }
    }
}
